package com.shujia.git;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class Demo4Login {
    public static void main(String[] args) throws Exception {

        //1、输入用户名和密码

        //控制台输入流
        InputStream in = System.in;

        //包装流
        Scanner scanner = new Scanner(in);

        System.out.println("请输入用户名:");
        String username = scanner.next();

        System.out.println("请输入密码:");
        String password = scanner.next();

        System.out.println(username + "\t" + password);

        /*
         *查询数据库判断用户名和密码是否正确
         *
         */

        //1、加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2、建立连接
        Connection con = DriverManager.getConnection("jdbc:mysql://master:3306/shujia", "root", "123456");

        //3、通过用户名查询用户
        PreparedStatement ps = con.prepareStatement("select username,password from user where username=?");

        //4、将用户名传参
        ps.setString(1, username);

        //5、执行sql
        ResultSet rs = ps.executeQuery();

        //6、判断用户是否存在
        if (!rs.next()) {
            System.out.println("用户名不存在");
            return;
        }

        //7、判断密码是否正确
        if (!password.equals(rs.getString("password"))) {
            System.out.println("密码输入错误，请重新输入密码");
            return;
        }

        System.out.println("登录成功");
    }
}
